package com.le.tester.javaThink.fourth.concurrency;

import com.le.tester.javaThink.fifth.chapter18_Str.Turtle;

import java.security.PublicKey;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Semaphore;

/**
 * createTime：2022/1/14 15:24
 * description：线程池中使用线程
 */
public class Pool<T> {
    private int size;

    private List<T> items = new ArrayList<>();

    private volatile boolean[] checkout;

    private Semaphore available;

    public Pool(Class<T> classObject, int size) {
        this.size = size;
        checkout = new boolean[size];
        //公平锁
        available = new Semaphore(size, true);

        for (int i = 0; i < size; ++i) {
            try {
                items.add(classObject.newInstance());
            } catch (Exception e) {
                throw new RuntimeException(e.getMessage());
            }
        }

    }

    public T checkOut() throws InterruptedException {
        available.acquire();
        return getItem();
    }

    public void checkIn(T x) {
        if (releaseItem(x)) {
            available.release();
        }
    }

    private synchronized T getItem() {
        for (int i = 0; i < size; ++i) {
            if (!checkout[i]) {
                checkout[i] = true;
                return items.get(i);
            }
        }
        return null;
    }

    private synchronized boolean releaseItem(T item) {
        int index = items.indexOf(item);
        if (index == -1) return false;
        if (checkout[index]) {
            checkout[index] = false;
            return true;
        }
        return false;
    }
}
